import { ModalForm, ProFormTextArea } from '@ant-design/pro-components';
import { Form, message } from 'antd';
import React, { useState } from 'react';
import { useIntl, useRequest } from '@umijs/max';
import {approveRequest} from '@/services/approval/api';

export type RejectFormProps = {
  values: API.ApprovalDetailViewItem;
  reload: () => void;
  trigger: React.ReactNode;
};

const RejectForm: React.FC<RejectFormProps> = (props) => {
  const { values, trigger } = props;
  const intl = useIntl();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();

  const [messageApi, contextHolder] = message.useMessage();

  const { run, loading } = useRequest(approveRequest, {
    manual: true,
    onSuccess: () => {
      messageApi.success('操作成功');
      setIsModalOpen(false);
      props.reload();
    },
    onError: () => {
      messageApi.error('操作失败，请重试');
      setIsModalOpen(false);
    },
  });

  const renderTrigger = () => {
    return <span onClick={() => setIsModalOpen(true)}>{trigger}</span>;
  };

  return (
    <>
      {contextHolder}
      {renderTrigger()}
      <ModalForm
        form={form}
        width={640}
        title={intl.formatMessage({
          id: 'pages.approvals.searchTable.rejectTitle',
          defaultMessage: '拒绝审批',
        })}
        open={isModalOpen}
        onOpenChange={setIsModalOpen}
        onFinish={async (formValues) => {
          await run({
            id: values.id,
            notes: formValues.reason,
            status: 0
          });
        }}
      >
        <ProFormTextArea
          name="reason"
          label="拒绝理由"
          placeholder="请输入拒绝理由"
          rules={[{ required: true, message: '请输入拒绝理由' }]}
        />
      </ModalForm>
    </>
  );
};

export default RejectForm;
